package utils;


import annotation.ThreadSafe;

import java.text.NumberFormat;
import java.util.concurrent.atomic.AtomicLong;

@ThreadSafe
public class AggrUtil {

    private final AtomicLong sum = new AtomicLong(0);
    private final AtomicLong frequency = new AtomicLong(0);
    private final AtomicLong min = new AtomicLong(Long.MAX_VALUE);
    private final AtomicLong max = new AtomicLong(Long.MIN_VALUE);

    //入参耗时
    public void calc(long time) {
        sum.addAndGet(time);
        frequency.incrementAndGet();
        min.updateAndGet((e) ->
                e > time ? time : e
        );
        max.updateAndGet((e) ->
                e > time ? e : time
        );
    }


    public String print() {
        StringBuilder sb = new StringBuilder("统计信息\n");
        sb.append("---------------------------------------------\n");
        sb.append("ns             name\n");
        sb.append("---------------------------------------------\n");
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMinimumIntegerDigits(20);
        nf.setGroupingUsed(false);
        NumberFormat pf = NumberFormat.getPercentInstance();
        pf.setMinimumIntegerDigits(2);
        pf.setGroupingUsed(false);

        sb.append(nf.format(frequency.get())).append("  ");
        sb.append("有效计算次数").append('\n');

        sb.append(nf.format(sum)).append("  ");
        sb.append("求和").append('\n');

        sb.append(nf.format(min)).append("  ");
        sb.append("最小值").append('\n');

        sb.append(nf.format(max)).append("  ");
        sb.append("最大值").append('\n');

        sb.append(nf.format(sum.get() / frequency.get())).append("  ");
        sb.append("平均值").append('\n');

        return sb.toString();

    }


}
